package com.brsya.movie.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.brsya.base.base.BaseMvpActivity;
import com.brsya.base.bean.UpdateBean;
import com.brsya.base.util.DownloadService;
import com.brsya.movie.R;
import com.brsya.movie.contract.UpdateContract;
import com.brsya.movie.fragment.FindFragment;
import com.brsya.movie.fragment.HomeFragment;
import com.brsya.movie.fragment.MeFragment;
import com.brsya.movie.fragment.MovieListFragment;
import com.brsya.movie.fragment.VideoFragment;
import com.brsya.movie.presenter.UpdatePresenter;
import com.brsya.movie.util.GeneralUtil;
import com.brsya.movie.widget.ExitDialog;
import com.brsya.movie.widget.TabLinearLayout;
import com.brsya.movie.widget.UpdateDialog;
import com.bytedance.sdk.dp.DPSdk;
import com.bytedance.sdk.dp.DPWidgetNewsParams;
import com.bytedance.sdk.dp.IDPNewsListener;
import com.bytedance.sdk.dp.IDPWidget;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Brsya
 * CreateDate: 2022/6/29  16:21
 * Description:
 * 首页
 */
public class HomeActivity extends BaseMvpActivity<UpdatePresenter> implements UpdateContract.View, View.OnClickListener, DownloadService.OnReceiveMessageListener {

    private final static int DEFAULT_TAB = 0;

    /**
     * 需要申请的权限数组
     */
    protected final String[] needInstallPermissions = {
            // 读取权限
            Manifest.permission.READ_EXTERNAL_STORAGE,
            // 写入权限
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };

    private FrameLayout flHomeFragmentBox;
    private ConstraintLayout clHomeTabBox;
    private TabLinearLayout llHomeTabMain;
    private TabLinearLayout llHomeTabFind;
    private TabLinearLayout llHomeTabNews;
    private TabLinearLayout llHomeTabVideo;
    private TabLinearLayout llHomeTabMe;


    private Map<Integer, Fragment> fragments;

    private int selectIndex;
    private long blackTime;
    private UpdateDialog updateDialog;
    private boolean downloadSuccess;
    private String downloadPath;
    private Handler mainHandler;
    private Runnable bookChangePaddingRunnable;


    private ExitDialog exitDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        mainHandler = new Handler(Looper.getMainLooper());
        initView();

        initViewData();

        fragments = new HashMap<>();
        selectTab(DEFAULT_TAB);
    }

    @Override
    protected void initPresenter() {
        presenter = new UpdatePresenter();
        presenter.attachView(this);
    }

    private void initView() {
        flHomeFragmentBox = findViewById(R.id.fl_home_fragment_box);
        clHomeTabBox = findViewById(R.id.cl_home_tab_box);
        llHomeTabMain = findViewById(R.id.ll_home_tab_main);
        llHomeTabFind = findViewById(R.id.ll_home_tab_find);
        llHomeTabNews = findViewById(R.id.ll_home_tab_news);
        llHomeTabVideo = findViewById(R.id.ll_home_tab_video);
        llHomeTabMe = findViewById(R.id.ll_home_tab_me);
    }

    private void initViewData() {
        llHomeTabMain.setOnClickListener(this);
        llHomeTabFind.setOnClickListener(this);
        llHomeTabNews.setOnClickListener(this);
        llHomeTabVideo.setOnClickListener(this);
        llHomeTabMe.setOnClickListener(this);

        llHomeTabMain.setIconResId(R.mipmap.icon_tab_home);
        llHomeTabMain.setIconCheckResId(R.mipmap.icon_tab_home_checked);
        llHomeTabMain.setTextColorUnCheck(0xFF999999);
        llHomeTabMain.setTextCheckColor(0xFFFF5BAA);
        llHomeTabMain.setText(getString(R.string.main_tab_home));
        llHomeTabFind.setIconResId(R.mipmap.icon_tab_find);
        llHomeTabFind.setIconCheckResId(R.mipmap.icon_tab_find_checked);
        llHomeTabFind.setTextColorUnCheck(0xFF999999);
        llHomeTabFind.setTextCheckColor(0xFFFF5BAA);
        llHomeTabFind.setText(getString(R.string.main_tab_find));
        llHomeTabNews.setIconResId(R.mipmap.icon_tab_news);
        llHomeTabNews.setIconCheckResId(R.mipmap.icon_tab_news_checked);
        llHomeTabNews.setTextColorUnCheck(0xFF999999);
        llHomeTabNews.setTextCheckColor(0xFFFF5BAA);
        llHomeTabNews.setText(getString(R.string.main_tab_news));
        llHomeTabVideo.setIconResId(R.mipmap.icon_tab_video);
        llHomeTabVideo.setIconCheckResId(R.mipmap.icon_tab_video_checked);
        llHomeTabVideo.setTextColorUnCheck(0xFF999999);
        llHomeTabVideo.setTextCheckColor(0xFFFF5BAA);
        llHomeTabVideo.setText(getString(R.string.main_tab_video));
        llHomeTabMe.setIconResId(R.mipmap.icon_tab_my);
        llHomeTabMe.setIconCheckResId(R.mipmap.icon_tab_my_checked);
        llHomeTabMe.setTextColorUnCheck(0xFF999999);
        llHomeTabMe.setTextCheckColor(0xFFFF5BAA);
        llHomeTabMe.setText(getString(R.string.main_tab_me));


        presenter.getUpdateLog();
        presenter.getPlayAddressNew();

        exitDialog = new ExitDialog(this);
        exitDialog.setOnClickBtnListener(new ExitDialog.OnClickBtnListener() {
            @Override
            public void onDismiss() {

            }

            @Override
            public void onConfirm() {
                HomeActivity.super.onBackPressed();
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_home_tab_main) {
            selectTab(0);
        } else if (id == R.id.ll_home_tab_find) {
            selectTab(1);
        } else if (id == R.id.ll_home_tab_news) {
            selectTab(2);
        } else if (id == R.id.ll_home_tab_video) {
            selectTab(3);
        } else if (id == R.id.ll_home_tab_me) {
            selectTab(4);
        }
    }

    @Override
    public void onBackPressed() {
        if (selectIndex != DEFAULT_TAB) {
            selectTab(DEFAULT_TAB);
            return;
        }
        //        if (System.currentTimeMillis() - blackTime > 2000) {
        //            blackTime = System.currentTimeMillis();
        //            showBackDialog();
        //            return;
        //        }


        exitDialog.show();

        //        super.onBackPressed();
    }

    /**
     * 显示退出弹框
     */
    private void showBackDialog() {
        // TODO: 2022/7/6  显示退出弹框
        Toast.makeText(this, "再次点击退出", Toast.LENGTH_SHORT).show();
    }

    /**
     * 选中TAB
     *
     * @param index 选中的位置
     */
    private void selectTab(int index) {
        if (index == 3) {
            clHomeTabBox.setBackgroundColor(0xFF000000);
            //            if (selectIndex != 3) {
            //                AppUtil.backgroundAnimation(clHomeTabBox, 0xFFFFFFFF, 0xFF000000, 200);
            //            }
            getWindow().setNavigationBarColor(0xFF000000);
            //            getWindow().setBackgroundDrawableResource(R.color.black);
        } else {
            clHomeTabBox.setBackgroundColor(0xFFFFFFFF);
            //            if (selectIndex == 3) {
            //                AppUtil.backgroundAnimation(clHomeTabBox, 0xFF000000, 0xFFFFFFFF, 200);
            //            }
            getWindow().setNavigationBarColor(0xFFFFFFFF);
            //            getWindow().setBackgroundDrawable(null);
        }


        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        for (Integer integer : fragments.keySet()) {
            fragmentTransaction.hide(fragments.get(integer));
        }
        if (fragments.get(index) == null) {
            Fragment fragment = createFragment(index);
            if (fragment == null) {
                Toast.makeText(this, "暂未开放", Toast.LENGTH_LONG).show();
                return;
            }
            fragments.put(index, fragment);
            fragmentTransaction.add(R.id.fl_home_fragment_box, fragment);
        } else {
            Fragment fragment = fragments.get(index);
            fragmentTransaction.show(fragment);
        }
        fragmentTransaction.commit();


        llHomeTabMain.setChecked(false);
        llHomeTabFind.setChecked(false);
        llHomeTabNews.setChecked(false);
        llHomeTabVideo.setChecked(false);
        llHomeTabMe.setChecked(false);


        switch (index) {
            case 0:
                llHomeTabMain.setChecked(true);
                break;
            case 1:
                llHomeTabFind.setChecked(true);
                break;
            case 2:
                llHomeTabNews.setChecked(true);
                break;
            case 3:
                llHomeTabVideo.setChecked(true);
                break;
            case 4:
                llHomeTabMe.setChecked(true);
                break;
        }
        selectIndex = index;
    }

    /**
     * 创建fragment
     *
     * @param index 创建的位置
     */
    private Fragment createFragment(int index) {
        Fragment fragment;
        switch (index) {
            case 0:
                HomeFragment homeFragment = HomeFragment.newInstance();
                homeFragment.setOnClickTabListener(new MovieListFragment.OnClickTabListener() {
                    @Override
                    public void onClickTab(int type) {
                        switch (type) {
                            case 0:
                                selectTab(2);
                                break;
                            case 1:
                                selectTab(3);
                                break;
                        }
                    }
                });
                fragment = homeFragment;
                break;
            case 1:
                // 2022/7/6 发现Fragment
                fragment = FindFragment.newInstance();
                break;
            case 2:
                // TODO: 2022/7/6 新闻Fragment
                try {

                    IDPWidget newsTabs = DPSdk.factory().createNewsTabs(DPWidgetNewsParams.obtain().listener(new IDPNewsListener() {}));
                    fragment = newsTabs.getFragment();
                    // 设置小说页面头部padding
                    Fragment finalFragment = fragment;
                    mainHandler.postDelayed(bookChangePaddingRunnable = new Runnable() {
                        @Override
                        public void run() {
                            View rootView = finalFragment.getView();
                            if (rootView == null) {
                                mainHandler.postDelayed(bookChangePaddingRunnable, 100);
                                return;
                            }
                            rootView.setPadding(
                                    rootView.getPaddingLeft(),
                                    rootView.getPaddingTop() + getStatusBarHeight(),
                                    rootView.getPaddingRight(),
                                    rootView.getPaddingBottom()
                            );
                        }
                    }, 100);
                } catch (Exception e) {
                    fragment = null;
                }
                break;
            case 3:
                // 2022/7/6 视频Fragment
                if (DPSdk.factory() == null) {
                    fragment = null;
                } else {
                    fragment = VideoFragment.newInstance();
                }
                break;
            case 4:
                // 2022/7/6 我的Fragment
                fragment = MeFragment.newInstance();
                break;
            default:
                fragment = null;
                break;
        }
        return fragment;
    }

    @Override
    public void showUpdateDialog(UpdateBean bean) {
        updateDialog = new UpdateDialog(this, bean);

        updateDialog.setOnClickBtnListener(new UpdateDialog.OnClickBtnListener() {
            @Override
            public void onDismiss() {

            }

            @Override
            public void onConfirm(UpdateBean updateBean) {
                if (permissionInstall()) {
                    if (downloadSuccess) {
                        Intent installAppIntent = GeneralUtil.getInstallAppIntent(HomeActivity.this, downloadPath);
                        startActivity(installAppIntent);
                        return;
                    }
                    DownloadService.addOnReceiveMessageListener(HomeActivity.this);
                    Intent intent = new Intent(HomeActivity.this, DownloadService.class);
                    intent.putExtra("downloadUrl", updateBean.getDownloadAddress());
                    startService(intent);
                } else {
                    ActivityCompat.requestPermissions(HomeActivity.this, needInstallPermissions, REQUEST_PERMISSION_CODE);
                }
            }
        });
        updateDialog.show();
    }

    /**
     * 是否授权 必要权限
     */
    private boolean permissionInstall() {
        return PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                && PackageManager.PERMISSION_GRANTED == ActivityCompat
                .checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }


    @Override
    public void startDownload(String goodsId) {
        updateDialog.updateProgress(0);
    }

    @Override
    public void setDownloadProgress(int progress) {
        if (progress >= 100) {
            downloadSuccess = true;
        } else {
            downloadSuccess = false;
        }
        updateDialog.updateProgress(progress);
    }

    @Override
    public void endDownload(String downloadPath) {
        if (downloadSuccess) {
            this.downloadPath = downloadPath;
            updateDialog.updateProgress(100);
            GeneralUtil.getInstallAppIntent(this, downloadPath);
        } else {
            error("未下载完成");
        }
    }

    @Override
    public void error(String msg) {
        downloadSuccess = false;
        updateDialog.downloadError();
    }

}
